<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use ReflectionException;
use PDOException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
//        'password',
//        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception $exception
     *
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception               $exception
     *
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        $status = 0;
        $error = '';
        $getMessage = '';

        /* http 404 */
        if ($exception instanceof NotFoundHttpException) {

            $error = 'Resource not found.';
            $status = 404;
            $getMessage = $exception->getMessage();

        } else if ($exception instanceof MethodNotAllowedHttpException) {

            $error = 'Resource not found.（method）';
            $status = 404;
            $getMessage = $exception->getMessage();

        } else if ($exception instanceof ReflectionException) {

            $error = 'Resource not found.（ReflectionException）';
            $status = 404;
            $getMessage = $exception->getMessage();

        } else if ($exception instanceof Exception) {

            $error = 'Resource not found.（Exception）';
            $status = 500;
            $getMessage = $exception->getMessage();


        } else if ($exception instanceof PDOException) {

            $error = 'Resource not found.（pdo）';
            $status = 500;
            $getMessage = $exception->getMessage();

        }

        if ($status != 0) {

            $url = $request->url();
            _writeBizException("http_status:{$status} , error:{$error} , exception:{$getMessage}，url:{$url}", __FUNCTION__, class_basename(__CLASS__));
            _writeBizException(json_encode(['request' => $request->all(), 'header' => $request->header(), 'ip' => JPGetRealIp()]), __FUNCTION__, class_basename(__CLASS__));

            return response()->json(['error' => $error], $status);
        }

        return parent::render($request, $exception);
    }
}
